package com.moleq.mgnetwork;

import java.io.File;
import java.util.Arrays;

public class FolderMonitor extends Thread {

	private static final int PADDING_FILE_COUNT = 10;
	private String dir;
	private int period;
	private boolean isError = false;
	private boolean running = false;
	private FileChangeCallback fileChangeCallback;
	private boolean pause = false;

	public FolderMonitor(String dir, int period, FileChangeCallback fileChangeCallback) {
		this.dir = dir;
		this.period = period;
		this.fileChangeCallback = fileChangeCallback;
	}
	
	public void pause(){
		this.pause  = true;
	}
	
	public void play(){
		this.pause = false;
	}

	@Override
	public void run() {

		running = true;

		while (running) {
			try {
				Thread.sleep(period * 1000);

				if (!pause) {
					File dirFile = new File(dir);
					File[] files;
					
					File[] paddingfiles;
					if (dirFile.isDirectory()) {

						// File[] files = dirFile.listFiles();
						files = listSortedFiles(dirFile);
						
						if (files != null && fileChangeCallback != null && files.length > 0){
							if (files.length > PADDING_FILE_COUNT) {
								paddingfiles = new File[PADDING_FILE_COUNT];
							}else{
								paddingfiles = new File[files.length];
							}
							
							for (int i = 0; i < paddingfiles.length; i++) {
								paddingfiles[i] = files[i];
							}
							
							fileChangeCallback.onProcessFiles(paddingfiles);
						}

					}
				}

			} catch (InterruptedException e) {
				System.out.println("对指定的文件路径进行监控时产生异常，异常信息为：" + e.getMessage());
				if (fileChangeCallback != null) {
					fileChangeCallback.onLog(e.getMessage());
				}
			}
		}

	}

	public void release() {
		running = false;
	}

	public interface FileChangeCallback {
		void onProcessFiles(File[] files);

		void onLog(String msg);
	}

	public File[] listSortedFiles(File dirFile) {
		assert dirFile.isDirectory();

		File[] files = dirFile.listFiles();

		FileWrapper[] fileWrappers = new FileWrapper[files.length];
		for (int i = 0; i < files.length; i++) {
			fileWrappers[i] = new FileWrapper(files[i]);
		}

		Arrays.sort(fileWrappers);

		File[] sortedFiles = new File[files.length];
		for (int i = 0; i < files.length; i++) {
			sortedFiles[i] = fileWrappers[i].getFile();
		}

		return sortedFiles;
	}

	class FileWrapper implements Comparable {
		/** File */
		private File file;

		public FileWrapper(File file) {
			this.file = file;
		}

		public int compareTo(Object obj) {
			assert obj instanceof FileWrapper;

			FileWrapper castObj = (FileWrapper) obj;

			if (this.file.getName().compareTo(castObj.getFile().getName()) > 0) {
				return 1;
			} else if (this.file.getName().compareTo(castObj.getFile().getName()) < 0) {
				return -1;
			} else {
				return 0;
			}
		}

		public File getFile() {
			return this.file;
		}
	}

}
